﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;
using System.Globalization;
using System.IO;

namespace SvD_Templates
{
    public partial class adTools : Form
    {
        private bool copy = false;
        private string user = "";
        private string pass = "";

        private string rutaLocalApp = @"C:\Program Files\SvD Templates\App";

        protected override bool ProcessDialogKey(Keys keyData)
        {
            switch (keyData)
            {
                case Keys.Escape:
                    this.Dispose();
                    break;

                case Keys.F1:
                    cajaNetID.ResetText();
                    cajaName.ResetText();
                    cajaEmail.ResetText();
                    cajaPhone.ResetText();
                    cajaLocation.ResetText();
                    cajaExchange.ResetText();
                    break;
            }

            return base.ProcessDialogKey(keyData);
        }

        public adTools()
        {
            InitializeComponent();
        }

        private void loadCredentials()
        {
            FileInfo file = new FileInfo(rutaLocalApp + "/AD");
            if (file.Exists)
            {
                StreamReader sr = new StreamReader(rutaLocalApp + "/AD");
                string temp = sr.ReadLine();
                string[] temp2 = temp.Split('|');
                user = temp2[0];
                pass = temp2[1];
                sr.Close();
            }
            else
            {
                MessageBox.Show("No existe archivo de credenciales.");
                this.Close();
            }
        }

        private void adTools_Load(object sender, EventArgs e)
        {
            loadCredentials();             
        }

        private string GetFilterString()
        {
            // form the filter string for directory search

            string filter = "";
            filter += FormFilter("user", cajaNetID.Text);

            return "(|" + filter + ")";
        }

        private string FormFilter(string objectCategory, string filter)
        {
            String result;
            result = String.Format("(&(objectCategory={0})(userPrincipalName={1}*))",
               objectCategory, filter);
            return result;
        }

        private void getNetIDADinfo()
        {
            try
            {
                DirectoryEntry de;
                de = new DirectoryEntry("LDAP://USINKOK-DC20.NORTHAMERICA.DELPHIAUTO.NET", "NORTHAMERICA\\" + user, pass, AuthenticationTypes.Secure);

                try
                {
                    DirectorySearcher search = new DirectorySearcher(de);
                    search.Filter = GetFilterString();
                    search.PropertiesToLoad.Add("displayName");
                    search.PropertiesToLoad.Add("mail");
                    search.PropertiesToLoad.Add("physicalDeliveryOfficeName");
                    search.PropertiesToLoad.Add("telephoneNumber");
                    search.PropertiesToLoad.Add("msExchHomeServerName");


                    SearchResult result = search.FindOne();

                    if (result != null)
                    {
                        cajaName.Text = result.Properties["displayName"][0].ToString() + Environment.NewLine;
                        cajaEmail.Text= result.Properties["mail"][0].ToString() + Environment.NewLine;
                        cajaPhone.Text = result.Properties["telephoneNumber"][0].ToString() + Environment.NewLine;

                        string tempLocation = result.Properties["physicalDeliveryOfficeName"][0].ToString();
                        TextInfo UStext = new CultureInfo("en-US", false).TextInfo;
                        string[] subTempLoca = tempLocation.Split('|');
                        cajaLocation.Text = UStext.ToTitleCase(subTempLoca[1].ToLower()) + Environment.NewLine;

                        string[] tempExchange = result.Properties["msExchHomeServerName"][0].ToString().Split('/');
                        cajaExchange.Text = tempExchange[5].Substring(3) + Environment.NewLine;
                    }
                    else
                    {
                        MessageBox.Show("User doesn't exist on AD.");
                    }
                }
                catch (Exception ex)
                {
                    string debug = ex.Message;
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void cajaNetID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13 && cajaNetID.Text.Length >= 6)
            {
                getNetIDADinfo();
            }
        }

        private void checkCopy_CheckedChanged(object sender, EventArgs e)
        {
            if (copy) copy = false;
            else
                copy = true;
        }

        private void cajaNetID_MouseClick(object sender, MouseEventArgs e)
        {
            if (copy && cajaNetID.Text != "")
                Clipboard.SetText(cajaNetID.Text);
        }

        private void cajaName_MouseClick(object sender, MouseEventArgs e)
        {
            if (copy && cajaName.Text != "")
                Clipboard.SetText(cajaName.Text);
        }

        private void cajaEmail_MouseClick(object sender, MouseEventArgs e)
        {
            if (copy && cajaEmail.Text != "")
                Clipboard.SetText(cajaEmail.Text);
        }

        private void cajaPhone_MouseClick(object sender, MouseEventArgs e)
        {
            if (copy && cajaPhone.Text != "")
                Clipboard.SetText(cajaPhone.Text);
        }

        private void cajaLocation_MouseClick(object sender, MouseEventArgs e)
        {
            if (copy && cajaLocation.Text != "")
                Clipboard.SetText(cajaLocation.Text);
        }

        private void cajaExchange_MouseClick(object sender, MouseEventArgs e)
        {
            if (copy && cajaExchange.Text != "")
                Clipboard.SetText(cajaExchange.Text);
        }

        private void label7_Click(object sender, EventArgs e)
        {
            loginForm login = new loginForm();
            login.ShowDialog();
            loadCredentials();
        }
    }
}
